package org.ilc.sample.util;

import net.sf.json.JSONObject;
import org.ilc.Bootstrap;
import org.ilc.sample.Constants;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

/**
 * 用户合法性校验器
 * @author malongbo
 */
public class AccountValidator{

    private static URL url = null;
    public static void init() {
        try {
            url = new URL (Bootstrap.getContext ().getAppConfig ().get (Constants.ACCOUNT_VALIDATOR_URL_KEY));
        } catch (Exception e) {
            e.printStackTrace ();
            throw new RuntimeException ("用户校验服务器地址错误", e);
        }
    }

    /**
     * 验证用户合法性
     * @param account
     * @param passwd
     * @param type
     * @return
     */
    public static boolean validateUser(String account, String passwd, String type, String version) {
        if (url == null)
            init ();

        Map<String, Object> params = new HashMap<String, Object> ();

        if (!ValidateUtil.validateStr (account) || !ValidateUtil.validateStr (passwd) || !ValidateUtil.validateStr (type))
            return false;

        params.put ("args[password]", passwd);
        params.put ("args[type]", type);
        params.put ("args[username]", account);
        params.put ("args[version]", version);
        params.put ("format", "JSON");
        params.put ("method", "Auth.login");
        params.put ("ts", System.currentTimeMillis ());

        String encodeResult = packageMap (params, true);

        String md5Result = CipherUtil.md5 (encodeResult);
        params.put ("sign", md5Result);

        String postData = packageMap (params, false);

        HttpURLConnection conn;

        try {
            conn = (HttpURLConnection) url.openConnection ();
            conn.setDoOutput (true);
            conn.setRequestMethod ("POST");

            conn.getOutputStream ().write (postData.getBytes ());
            conn.getOutputStream ().flush ();
            conn.getOutputStream ().close ();

            InputStreamReader reader = new InputStreamReader (conn.getInputStream ());

            BufferedReader breader = new BufferedReader (reader);

            StringBuffer stringBuffer = new StringBuffer ();

            String content = null;
            while (true) {
                content = breader.readLine ();
                if (content == null) {
                    breader.close ();
                    break;
                }

                stringBuffer.append (content);
            }

            System.out.println (postData);
            System.out.println (stringBuffer.toString ());
            JSONObject jsonObject = JSONObject.fromObject (stringBuffer.toString ());
            Object errCode = jsonObject.get ("errCode");

            if (errCode != null)
                return false;
            /*if (ValidateUtil.validateStr (errCode))
                return false;*/
        } catch (IOException e) {
            e.printStackTrace ();
        }


        return true;
    }

    /**
     *
     * @param params
     * @param isEncode
     * @return
     */
    private static String packageMap (Map<String, Object> params, boolean isEncode) {
        List<String> keys = new ArrayList<String> ();

        Set<String> keySet = params.keySet ();
        int keysCount = keySet.size ();
        String[] temp = new String[keysCount];
        keySet.toArray (temp);
        Arrays.sort (temp);

        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < keysCount; i++ ) {
            String s1 = temp[i];
            if (isEncode)
                s1 = URLEncoder.encode (temp[i]);
            if (i != 0) {buffer.append("&");}
            buffer.append (s1 + "=" + params.get (temp[i]));
        }
        return buffer.toString ();
    }


}
